/*
@hehung
2023-7-15
email: 1398660197@qq.com
wechat: hehung95
reproduced and please indicate the source @hehung
*/

#include "app_common.h"


#define RTC_DEBUG
#undef RTC_DEBUG

#ifdef RTC_DEBUG
#include <stdio.h>
#define LOG(fmt, ...) 	                printf(fmt, ##__VA_ARGS__)
#else
#define LOG(fmt, ...)
#endif

#define RTC_ALARM_EN        (COMM_OFF)


/* rtc_time_t is an alias for the C Standard time.h struct 'tm' */
rtc_time_t set_time =
{
    .tm_sec  = 0,      /* 秒，范围从 0 到 59 */
    .tm_min  = 30,      /* 分，范围从 0 到 59 */
    .tm_hour = 12,      /* 小时，范围从 0 到 23*/
    .tm_mday = 15,       /* 一月中的第几天，范围从 1 到 31*/
    .tm_mon  = 7,      /* 月份，范围从 0 到 11*/
    .tm_year = 123,     /* 自 1900 起的年数，2021为121*/
    .tm_wday = 6,       /* 一周中的第几天，范围从 0 到 6*/
//    .tm_yday=0,         /* 一年中的第几天，范围从 0 到 365*/
//    .tm_isdst=0;        /* 夏令时*/
};

#if (RTC_ALARM_EN == COMM_ON)
rtc_alarm_time_t set_alarm_time=
{
     .time.tm_sec  =   5,
     .time.tm_sec  = 5,      /* 秒，范围从 0 到 59 */
     .time.tm_min  = 30,      /* 分，范围从 0 到 59 */
     .time.tm_hour = 12,      /* 小时，范围从 0 到 23*/
     .time.tm_mday = 20,       /* 一月中的第几天，范围从 1 到 31*/
     .time.tm_mon  = 11,      /* 月份，范围从 0 到 11*/
     .time.tm_year = 121,     /* 自 1900 起的年数，2021为121*/
     .time.tm_wday = 5,       /* 一周中的第几天，范围从 0 到 6*/

     .sec_match        =  1,
     .min_match        =  0,
     .hour_match       =  0,
     .mday_match       =  0,
     .mon_match        =  0,
     .year_match       =  0,
     .dayofweek_match  =  0,
};
#endif

// notification of rtc
void rtc_notification(rtc_callback_args_t *p_args)
{
	(void)p_args;
    /* TODO: add your own code here */
    // if(p_args->event == RTC_EVENT_PERIODIC_IRQ)
    //     rtc_flag=1;
    // else if(p_args->event == RTC_EVENT_ALARM_IRQ)
    //     rtc_alarm_flag=1;
}


void Rtc_Init(void)
{
    fsp_err_t err = FSP_SUCCESS;
	rtc_time_t setting_t;

    /* Initialize the RTC module*/
    err = R_RTC_Open(&g_rtc0_ctrl, &g_rtc0_cfg);
    /* Handle any errors. This function should be defined by the user. */
    assert(FSP_SUCCESS == err);
    /* R_RTC_CalendarTimeSet must be called at least once to start the RTC */
	setting_t = Rtc_GetDateTime();
    R_RTC_CalendarTimeSet(&g_rtc0_ctrl, &setting_t);
    /* Set the periodic interrupt rate to 1 second */
    R_RTC_PeriodicIrqRateSet(&g_rtc0_ctrl, RTC_PERIODIC_IRQ_SELECT_1_SECOND);

#if (RTC_ALARM_EN == COMM_ON)
    /* Set alarm time */
    R_RTC_CalendarAlarmSet(&g_rtc0_ctrl, &set_alarm_time);
#endif
}

void Rtc_SetTime(rtc_time_t datetime)
{
	R_RTC_CalendarTimeSet(&g_rtc0_ctrl, &datetime);
}

// get date-time
rtc_time_t Rtc_GetDateTime(void)
{
    rtc_time_t get_time;

    // get rtc time
    (void)R_RTC_CalendarTimeGet(&g_rtc0_ctrl, &get_time);

    LOG ("RTC: %d-%d-%d, %d:%d:%d, %dw\r\n", get_time.tm_year + 1900,
                                           get_time.tm_mon,
                                           get_time.tm_mday,
                                           get_time.tm_hour,
                                           get_time.tm_min,
                                           get_time.tm_sec,
                                           get_time.tm_wday);

    return get_time;
}

rtc_time_t Rtc_StrtoTime(char *time_str)
{
    int year, day, hour, minute, second;
    char month[4] = {0}, week[4] = {0};
    rtc_time_t curr_t = 
	{
		.tm_year = 1970,
		.tm_mon = 0,
		.tm_mday = 1,
		.tm_hour = 0,
		.tm_min = 0,
		.tm_sec = 0,
		.tm_wday = 0
	};
    uint8_t i;

    const char *month_str_arr[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    const char *week_str_arr[] = {"Sun", "Mon", "Tue", "Wed",
                                "Thu", "Fri", "Sat"};

    if (sscanf(time_str, "%s %s %d %d:%d:%d %d", week, month, &day, &hour, &minute,
                &second, &year) != 7) 
    {
        LOG ("RTC: Time string is wrong\r\n");
    }
	
	curr_t.tm_year = year - 1900;
	curr_t.tm_mday = day;
	curr_t.tm_hour = hour;
	curr_t.tm_min = minute;
	curr_t.tm_sec = second;

    // Find week
    for (i = 0; i < 7; i++)
    {
        if (strcmp(week, week_str_arr[i]) == 0) 
        {
            curr_t.tm_wday = i;
            break;
        }
    }

    // Find month
    for (i = 0; i < 12; i++)
    {
        if (strcmp(month, month_str_arr[i]) == 0) 
        {
            curr_t.tm_mon = i;
            break;
        }
    }

    return curr_t;
}
